/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lbim.server.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import lbim.server.data.MessageStore;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *
 * @author Jestan
 */
public class CirServerHandler extends IoHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(CirServerHandler.class);

    private Set<String> sessions = new HashSet<String>();

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        session.close(true);
    }

    @Override
    public void messageReceived(IoSession session, Object o) {
        String message = (String) o;
        if (isHelloMsg(session)) {
            processHelloMsg(session, message);
            session.write("OK\r\n");
        } else if(message.equals("CLOSE")) {
            String sid = (String) session.getAttribute("sid");
            logger.info("CIR session is closed by client sid:"+sid);
            sessions.remove(sid);
            session.write("OK\r\n");
        } else {
            String sid = (String) session.getAttribute("sid");
            if (MessageStore.isAck(sid)) {
                session.write("NM\r\n");
            } else {
                session.write("OK\r\n");
            }
        }

    }

    @Override
    public void sessionClosed(IoSession session) {
        logger.info("CIR session successfuly closed");
    }

    @Override
    public void sessionCreated(IoSession session) {
     session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 120);
     session.setAttribute("hello", "true");
     logger.info("CIR session created ");
    }

    private boolean isHelloMsg(IoSession session) {
        String init = (String) session.getAttribute("hello");
        return Boolean.valueOf(init);
    }

    private void processHelloMsg(IoSession session, String message) {
        StringTokenizer tokenizer = new StringTokenizer(message, ":");
        ArrayList<String> helloMsg = new ArrayList<String>();
        while (tokenizer.hasMoreElements()) {
            helloMsg.add((String) tokenizer.nextElement());
        }
        String userName = helloMsg.get(0);
        String sid = helloMsg.get(1);
        session.setAttribute("username", userName);
        session.setAttribute("sid", sid);
        sessions.add(sid);
        session.setAttribute("hello", "false");
        logger.info("CIR hello message username:" + userName + " sid:" + sid);
    }

    public int getCurrentSessions() {
        return sessions.size();
    }

}
